//
//  AppViewController.m
//  IconMaster
//
//  Created by 为为 on 14-8-23.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "AppViewController.h"
#import "AppCell.h"
#import "DBUtil.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "UIAlertView+Blocks.h"
//#import "Util/Util.h"
#import "Util.h"

@interface AppViewController ()
{
	int itemCount;
	NSMutableDictionary* itemDict;
	NSString* searchWords;
}

@end

@implementation AppViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view from its nib.
    UIImageView *navImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 64)];
    navImage.image = [UIImage imageNamed:@"navall"];
    [self.view addSubview:navImage];
    [navImage sendSubviewToBack:self.view];
    
    [self setBarType];
	itemCount = 0;
	itemDict = [NSMutableDictionary dictionary];
	
	[self initSearchBar];
	[self initNavigationItem];
	[self reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark tableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return itemCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	AppCell* cell = [tableView dequeueReusableCellWithIdentifier:@"AppCell"];
	if (!cell) {
		cell = [AppCell getCell];
	}
	[self provideDataForCell:cell indexPath:indexPath];
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSDictionary* dict = [self getDataForIndex:indexPath.row];
	if (1) {
//	if ([self canOpenUrl:[dict objectForKey:@"scheme"]]) {
        if (self.appSelectedBlock) {
            self.appSelectedBlock(self, dict);
        }
	} else {
        NSString* cancelTitle = NSLocalizedString(@"Cancel", @"");
        NSString* okTitle = NSLocalizedString(@"OK", @"");
        [UIAlertView showWithTitle:nil
                           message:NSLocalizedString(@"install hint", @"")
                             style:UIAlertViewStyleDefault
                 cancelButtonTitle:cancelTitle
                 otherButtonTitles:@[okTitle]
                          tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                              if (buttonIndex == [alertView cancelButtonIndex]) {
                                  
                              } else if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:okTitle]) {
                                  [self showStoreWithAppID:[dict objectForKey:@"appid"]];
                              }
                          }];
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static AppCell* cell;
	if (!cell) {
		cell = [AppCell getCell];
	}
	return cell.frame.size.height;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	[self.msearchBar resignFirstResponder];
}

#pragma mark store kit

- (void)showStoreWithAppID:(NSString*)appid
{
	JumpToAppStoreWithAppID(appid);
}

#pragma mark table data

- (void)provideDataForCell:(AppCell*)cell indexPath:(NSIndexPath*)indexPath
{
	NSDictionary* dict = [self getDataForIndex:indexPath.row];
	cell.nameLabel.text = [dict objectForKey:@"name"];
	
	NSURL* imageUrl = [NSURL URLWithString:[dict objectForKey:@"iconlink"]];
	[cell.iconImageView sd_setImageWithURL:imageUrl placeholderImage:nil];
}

- (void)reloadData
{
	searchWords = self.msearchBar.text;
	[self reloadDataWithQuery:searchWords];
	[self.mtableView reloadData];
}

- (void)reloadDataWithQuery:(NSString*)query
{
    [itemDict removeAllObjects];
    
	NSArray* resultArray = [DBUtil query:@"select count(*) as count from app where name like %@", [NSString stringWithFormat:@"%%%@%%", query]];
	if (resultArray.count) {
		NSDictionary* resultDict = [resultArray objectAtIndex:0];
		itemCount = [[resultDict objectForKey:@"count"] intValue];
		[self getDataForIndex:0];
	} else {
		itemCount = 0;
	}
}

- (void)loadDataBeginAtIndex:(NSUInteger)index number:(NSUInteger)number query:(NSString*)query
{
	NSArray* results = [DBUtil query:@"select name,appid,scheme,link,iconlink from app where name like %@ order by length(name) limit %u, %u ", [NSString stringWithFormat:@"%%%@%%", query], (unsigned int)index, (unsigned int)number];
	for (int i=0; i<results.count; i++) {
		NSDictionary* dict = [results objectAtIndex:i];
		[itemDict setObject:dict forKey:[NSString stringWithFormat:@"%u",i+(unsigned int)index]];
	}
}

- (NSDictionary*)getDataForIndex:(NSUInteger)index
{
	NSString* key = [NSString stringWithFormat:@"%u", (unsigned int)index];
	NSDictionary* dict = [itemDict objectForKey:key];
	if (!dict) {
		[self loadDataBeginAtIndex:index number:40 query:searchWords];
//        NSLog(@"load data for %d", index);
	}
	dict = [itemDict objectForKey:key];
	return dict;
}

#pragma mark search bar 

- (void)initSearchBar
{
	self.msearchBar.placeholder = NSLocalizedString(@"Search more apps", @"");
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];
    [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.8];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	[self reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
//	NSLog(@"cancel clicked");
}

#pragma mark navigation bar

- (void)initNavigationItem {
	UIImage* image = [UIImage imageNamed:@"close_button.png"];
    CGFloat imageWidth = 22;
	if (image.size.width > imageWidth) {
		image = [CImageUtil imageFromImage:image scaleToSize:CGSizeMake(imageWidth, imageWidth)];
	}
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonPressed:)];
}

#pragma mark open url

- (BOOL)canOpenUrl:(NSString*)urlString
{
    urlString = NormalizeUrlScheme(urlString);
	return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]];
}

#pragma mark action

- (IBAction)cancelButtonPressed:(id)sender {
	if (self.cancelBlock) {
		self.cancelBlock(self);
	}
}

@end
